import axios from "axios";
import router from "@/router";

//axios对象的创建
const request = axios.create({
    baseURL:"http://localhost:8080",
    withCredentials:false,
    timeout:5000
})
//设置请求头信息
request.defaults.headers["Content-Type"]="application/json;charset=utf-8";

let token = "";
request.interceptors.request.use(
    config=>{
        if(token){
            config.headers["Authorization"] = token;
        }
        return config;
    },
    error=>{
        return Promise.reject(error);
    }
)

request.interceptors.response.use(
    response=>{
       /*
            Result:
            {
                "msg":,
                "code":,
                "data":
            }
       */ 
       let {msg,code} = response.data;
       console.log(msg,code);
        if (code == 200) {
          ElMessage.success(msg);
          return response.data;
        } else if (code == 500) {
          ElMessage.error("服务端异常!!!");
        } else if (code == 401) {
          ElMessage.error("没有操作权限!!!");
        } else if (code == 403) {
          ElMessage.error("登陆过期!!!");
          //清除pinia、sessionStorage中的数据
          window.sessionStorage.clear();
          router.push('/login');

        }
        return Promise.reject(new Error(msg));
    },
    error=>{
        ElMessage.error("没有操作权限!!!");
        window.sessionStorage.clear();
        router.push("/login");
        return Promise.reject(error);
    }
)

export default request;